import Toast from '../../../../miniprogram_npm/@vant/weapp/toast/toast';
const $api = require('../../../../request/api').API;
Page({
  data: {
    show: false,
    currentDate: new Date().getTime(),
    year: new Date().getFullYear(),
    month: new Date().getMonth() + 1,
    expense: 0,
    income: 0,
    pag: {
      pageNo: 1,
      pageSize: 10,
      totalPage: 0
    },
    dataList: []
  },
  onLoad: function (options) {
    this.fetchIncomeExpenditurePoints();
    this.fetchPointsRecord();
  },
  onReachBottom() {
    const { pag, dataList, year, month } = this.data;
    if (pag.pageNo < pag.totalPage) {
      $api.customerPointsPage({ year, month, pageNo: pag.pageNo + 1, pageSize: pag.pageSize }).then(res => {
        const list = res.data.data.list;
        this.setData({
          dataList: dataList.concat(list),
          pag: { ...pag, pageNo: pag.pageNo + 1 }
        });
      });
    } else {
      Toast('没有更多啦');
    }
  },

  /**
   * 根据月份统计收入支出积分
   */
  fetchIncomeExpenditurePoints() {
    const { year, month } = this.data;
    $api.countByMonth({ year, month }).then(res => {
      const { expense, income } = res.data.data;
      this.setData({ expense, income });
    });
  },

  /**
   * 积分记录
   */
  fetchPointsRecord() {
    const { year, month, pag } = this.data;
    $api.customerPointsPage({ year, month, ...pag }).then(res => {
      const data = res.data.data;
      this.setData({ dataList: data.list, pag: { ...pag, totalPage: data.totalPage } });
    });
  },

  handleSelectTime() {
    this.setData({ show: true });
  },
  handleDatetimepickerCancel() {
    this.setData({ show: false });
  },
  handleDatetimepickerConfirm(event) {
    const time = new Date(event.detail);
    const year = time.getFullYear();
    const month = time.getMonth() + 1;
    this.setData(
      { show: false, currentDate: event.detail, year, month, pag: { ...this.data.pag, pageNo: 1, totalPage: 0 } },
      () => {
        this.fetchIncomeExpenditurePoints();
        this.fetchPointsRecord();
      }
    );
  }
});
